/*
 * 
 *  This file is part of Sourceprojects.org Lycia Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.lycia.internal.platform.base;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.sourceprojects.lycia.annotations.Attribute;
import org.sourceprojects.lycia.exceptions.LyciaConfigurationException;
import org.sourceprojects.lycia.internal.generator.Parameter;
import org.sourceprojects.lycia.internal.generator.ParameternameAnalyserUtils;
import org.sourceprojects.lycia.internal.platform.AttributeNameFindingStrategy;

public class BytecodeAttributeNameFindingStrategyImpl<B> implements
		AttributeNameFindingStrategy<B> {

	private final Map<Method, Parameter[]> PARAMETER_CACHE = new HashMap<Method, Parameter[]>();

	@Override
	public String findAttributeName(Method method, int index) {
		Annotation[][] annotations = method.getParameterAnnotations();

		for (Annotation annotation : annotations[index]) {
			if (annotation.annotationType().equals(Attribute.class)) {
				Attribute attribute = (Attribute) annotation;

				if (!Attribute.NULL.equals(attribute.value())) {
					return attribute.value();
				}
			}
		}

		Parameter[] parameters = PARAMETER_CACHE.get(method);

		if (parameters == null) {
			parameters = ParameternameAnalyserUtils.getParameter(method);

			if (parameters.length <= index) {
				throw new LyciaConfigurationException(
						"Parametername could not be retrieved from bytecode -"
								+ " parametercount did not matched");
			}

			PARAMETER_CACHE.put(method, parameters);
		}

		Parameter parameter = parameters[index];

		if (!parameter.getType().equals(method.getParameterTypes()[index])) {
			throw new LyciaConfigurationException(
					"Parametername could neither be retrieved from "
							+ "bytecode nor by @Attribute annotation");
		}

		return parameter.getName();
	}
}
